package cn.tedu.luban.demand.main.rpc;

import cn.tedu.luban.demand.api.DemandApi;
import cn.tedu.luban.demand.main.service.DemandOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DemandApiImpl implements DemandApi {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String REQUEST_ORDER_LOCK="luban:request:";

    @Autowired
    private DemandOrderService demandOrderService;

    @Override
    public Boolean grabOrder(String requestOrderNo) {
        //设计锁的key值
        String garbKey=REQUEST_ORDER_LOCK+requestOrderNo;
        //执行redis的api方法抢锁，设置自动超时时间
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        //setnx:当key不存在时，才会新增成功，并返回true，如果key存在，则新增失败，返回false
        Boolean tryLock = opsForValue.setIfAbsent(garbKey, "", 5, TimeUnit.SECONDS);
        Boolean grabOk=false;
        if (tryLock) {
            //调用业务层方法
            grabOk=demandOrderService.grabOrder(requestOrderNo);
        }
        return grabOk;
    }

    @Override
    public Boolean returnOrder(String requestOrderNo) {
        return demandOrderService.returnOrder(requestOrderNo);
    }
}
